<template>
  <transition name="chat-floating-fade">
    <div
      v-show="isLoggedIn"
      ref="buttonRef"
      class="chat-floating-button"
      :style="buttonStyle"
      @mousedown.prevent="startDrag"
      @touchstart.prevent="startDrag"
      @click.stop="handleClick"
    >
      <img :src="iconUrl" alt="聊天" />
      <span v-if="unreadCount > 0" class="badge">{{ unreadCount > 99 ? '99+' : unreadCount }}</span>
    </div>
  </transition>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import useChatStore from '@/store/modules/chat'
import { useAgentStore } from '@/store/modules/agent'
import useUserStore from '@/store/modules/user'
import { getToken } from '@/utils/auth'
import iconUrl from '@/assets/chat-bubble.png'

const chatStore = useChatStore()
const agentStore = useAgentStore()
const userStore = useUserStore()

// 检查用户是否已登录
const isLoggedIn = computed(() => {
  return !!userStore.token
})

const buttonRef = ref(null)
const isDragging = ref(false)
const startX = ref(0)
const startY = ref(0)
const startRight = ref(0)
const startBottom = ref(0)
const buttonWidth = ref(60)
const buttonHeight = ref(47)

const unreadCount = computed(() => chatStore.unreadCount)

const buttonStyle = computed(() => ({
  right: `${chatStore.floatingPosition.right}px`,
  bottom: `${chatStore.floatingPosition.bottom}px`
}))

const handleClick = async () => {
  if (isDragging.value) return
  
  console.log('[FloatingChatButton] 点击浮动按钮，准备打开聊天窗口')
  
  // ✅ 如果agentStore客户端列表为空，先加载客户端列表
  if (!agentStore.clients || agentStore.clients.length === 0) {
    console.log('[FloatingChatButton] 客户端列表为空，开始加载...')
    try {
      const { getAgentClientList } = await import('@/api/agent')
      const res = await getAgentClientList({ page_num: 1, page_size: 1000 })
      
      // ✅ 兼容两种数据格式：res.data.rows 或 res.rows
      const clientList = res.data?.rows || res.rows || []
      
      if (res.code === 200 && clientList.length > 0) {
        agentStore.setClients(clientList.map(client => ({
          ...client,
          client_type: client.client_type || '',
          online_status: client.online_status || 'offline',
          login_status: client.login_status || 'not_logged_in'
        })))
        console.log('[FloatingChatButton] ✅ 已加载客户端列表:', clientList.length, '个客户端')
        
        // ✅ 统计各类型客户端数量
        const orderCount = clientList.filter(c => c.client_type === 'order').length
        const searchCount = clientList.filter(c => c.client_type === 'search').length
        const standbyCount = clientList.filter(c => c.client_type === 'standby').length
        console.log(`[FloatingChatButton] 客户端类型统计: order=${orderCount}, search=${searchCount}, standby=${standbyCount}`)
      } else {
        console.error('[FloatingChatButton] ❌ 加载客户端列表失败或列表为空')
        console.error('[FloatingChatButton] 响应code:', res.code)
        console.error('[FloatingChatButton] clientList长度:', clientList.length)
      }
    } catch (error) {
      console.error('[FloatingChatButton] ❌ 加载客户端列表异常:', error)
      console.error('[FloatingChatButton] 错误详情:', error.message, error.stack)
    }
  } else {
    console.log('[FloatingChatButton] 客户端列表已存在:', agentStore.clients.length, '个客户端')
  }
  
  // ✅ 等待一小段时间确保agentStore更新完成
  await new Promise(resolve => setTimeout(resolve, 100))
  
  // ✅ 如果当前没有选中的客户端，尝试自动选择第一个可用的
  if (!chatStore.selectedClientId) {
    console.log('[FloatingChatButton] 当前未选中客户端，尝试自动选择...')
    console.log('[FloatingChatButton] agentStore.clients:', agentStore.clients?.length || 0, '个')
    
    const availableClients = (agentStore.clients || []).filter(c => {
      const isOrder = c.client_type === 'order'
      const isOnline = c.online_status === 'online'
      const isLoggedIn = c.login_status === 'logged_in'
      
      console.log(`[FloatingChatButton] 检查客户端 ${c.client_id}:`, {
        client_type: c.client_type,
        isOrder,
        online_status: c.online_status,
        isOnline,
        login_status: c.login_status,
        isLoggedIn,
        符合条件: isOrder && isOnline && isLoggedIn
      })
      
      return isOrder && isOnline && isLoggedIn
    })
    
    console.log('[FloatingChatButton] 可用客户端:', availableClients.length, '个')
    if (availableClients.length > 0) {
      console.log('[FloatingChatButton] ✅ 自动选择客户端:', availableClients[0].client_id)
      chatStore.selectClient(availableClients[0].client_id)
    } else {
      console.error('[FloatingChatButton] ❌ 没有可用的下单客户端（需要client_type=order且在线且已登录）')
      // ✅ 导入ElMessage
      const { ElMessage } = await import('element-plus')
      ElMessage.warning('没有可用的下单客户端，请先在账号管理页面启动并登录下单主机')
    }
  } else {
    console.log('[FloatingChatButton] 已选中客户端:', chatStore.selectedClientId)
  }
  
  // ✅ 最后打开聊天窗口（确保客户端已选择）
  chatStore.setVisible(true)
}

const startDrag = (event) => {
  isDragging.value = false
  const rect = buttonRef.value?.getBoundingClientRect()
  if (rect) {
    buttonWidth.value = rect.width
    buttonHeight.value = rect.height
  }
  const point = getPoint(event)
  startX.value = point.x
  startY.value = point.y
  startRight.value = chatStore.floatingPosition.right
  startBottom.value = chatStore.floatingPosition.bottom

  document.addEventListener('mousemove', handleMove)
  document.addEventListener('mouseup', stopDrag)
  document.addEventListener('touchmove', handleMove, { passive: false })
  document.addEventListener('touchend', stopDrag)
}

const handleMove = (event) => {
  event.preventDefault()
  const point = getPoint(event)
  const deltaX = point.x - startX.value
  const deltaY = point.y - startY.value

  if (!isDragging.value) {
    const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY)
    if (distance < 4) return
    isDragging.value = true
  }

  const maxRight = Math.max(16, window.innerWidth - buttonWidth.value - 16)
  const maxBottom = Math.max(16, window.innerHeight - buttonHeight.value - 16)

  let newRight = startRight.value - deltaX
  let newBottom = startBottom.value - deltaY

  newRight = Math.min(Math.max(newRight, 16), maxRight)
  newBottom = Math.min(Math.max(newBottom, 16), maxBottom)

  chatStore.setFloatingPosition({
    right: newRight,
    bottom: newBottom
  })
}

const stopDrag = () => {
  document.removeEventListener('mousemove', handleMove)
  document.removeEventListener('mouseup', stopDrag)
  document.removeEventListener('touchmove', handleMove)
  document.removeEventListener('touchend', stopDrag)

  setTimeout(() => {
    isDragging.value = false
  }, 0)
}

const getPoint = (event) => {
  if (event.touches && event.touches[0]) {
    return { x: event.touches[0].clientX, y: event.touches[0].clientY }
  }
  return { x: event.clientX, y: event.clientY }
}

onMounted(() => {
  // 当窗口尺寸变化时，确保浮标仍在可视区域
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
})

const handleResize = () => {
  const rect = buttonRef.value?.getBoundingClientRect()
  if (rect) {
    buttonWidth.value = rect.width
    buttonHeight.value = rect.height
  }
  const maxRight = Math.max(16, window.innerWidth - buttonWidth.value - 16)
  const maxBottom = Math.max(16, window.innerHeight - buttonHeight.value - 16)
  chatStore.setFloatingPosition({
    right: Math.min(chatStore.floatingPosition.right, maxRight),
    bottom: Math.min(chatStore.floatingPosition.bottom, maxBottom)
  })
}
</script>

<style scoped>
.chat-floating-button {
  position: fixed;
  width: 60px;
  aspect-ratio: 257 / 200;
  z-index: 2200;
  cursor: pointer;
  user-select: none;
  transition: transform 0.2s ease;
}

.chat-floating-button:hover {
  transform: translateY(-2px);
}

.chat-floating-button img {
  width: 100%;
  height: 100%;
  display: block;
  object-fit: contain;
}

.chat-floating-button .badge {
  position: absolute;
  top: -4px;
  right: -4px;
  min-width: 20px;
  padding: 0 5px;
  height: 20px;
  line-height: 20px;
  border-radius: 10px;
  background: #f56c6c;
  color: #fff;
  font-size: 12px;
  text-align: center;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
}

.chat-floating-fade-enter-active,
.chat-floating-fade-leave-active {
  transition: opacity 0.2s ease;
}

.chat-floating-fade-enter-from,
.chat-floating-fade-leave-to {
  opacity: 0;
}
</style>

